package com.nulldev.util.networking.npacket4.iprotocols.ncryptx;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import com.nulldev.util.networking.npacket4.nPacket;
import com.nulldev.util.networking.npacket4.extensions.PacketExtension;

public class nCryptKeyShareMeta extends nPacket {

	private static final long serialVersionUID = 4675262687953062921L;
	private KeyExchangeMethod[] supportedMethods;
	private byte cryptVersion = nCryptX.CRYPT_VERSION;

	public nCryptKeyShareMeta(final nPacket packet) {
		super("ncryptx.key_share_meta", packet);
	}

	public nCryptKeyShareMeta(final KeyExchangeMethod[] supportedMethods, final PacketExtension... exts) {
		super("ncryptx.key_share_meta", exts);
		this.supportedMethods = supportedMethods;
	}

	@Override
	public void onGenerate(final DataOutputStream dos) throws IOException {
		dos.writeByte(this.cryptVersion);
		dos.writeInt(this.supportedMethods.length);
		for (final KeyExchangeMethod m : this.supportedMethods)
			dos.writeShort(m.id());
		dos.flush();
	}

	@Override
	public void onPacket(final DataInputStream dis) throws IOException {
		final byte cryptAPIVersion = dis.readByte();
		final int length = dis.readInt();
		final KeyExchangeMethod[] m = new KeyExchangeMethod[length];
		for (int i = 0; i < length; i++) {
			m[i] = KeyExchangeMethod.get(dis.readShort());
		}
		this.supportedMethods = m;
		this.cryptVersion = cryptAPIVersion;
	}

	public KeyExchangeMethod[] getMethods() {
		return this.supportedMethods;
	}

	public byte getCryptVersion() {
		return this.cryptVersion;
	}
}
